<template>
  <el-card class="box">
    <div class="top">
      <span style="font-size: 25px; color: #203857">公告栏</span>
    </div>
    <el-table :data="announcements" height="400px" stripe>
      <el-table-column
        type="index"
        label="序号"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="author"
        label="发布人"
        align="center"
        width="100px"
      ></el-table-column>
      <el-table-column prop="title" label="标题" align="center">
        <!-- 标题指定颜色为409EFF 和文件数量无关-->
        <template #default="{ row }">
          <span :style="'color:#388AF6;'">
            {{ row.title }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="发布时间"
        align="center"
        width="150px"
      ></el-table-column>
      <el-table-column
        prop="deadLine"
        label="截止时间"
        align="center"
        width="150px"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="150px">
        <template #default="{ row }">
          <div class="button-group">
            <el-button
              title="查看详情"
              type="primary"
              size="small"
              @click="showDetails(row)"
              plain
              circle
            >
              <el-icon><View /></el-icon>
            </el-button>
            <el-button
              title="下载附件"
              type="warning"
              size="small"
              plain
              circle
              :disabled="isFileCountPassed(row.fileCount)"
              @click="downloadAttachments(row.id, row.title)"
            >
              <el-icon><Download /></el-icon>
            </el-button>
            <el-upload
              :ref="
                (el) => {
                  if (el) uploadRefs[row.id] = el;
                }
              "
              :auto-upload="false"
              :show-file-list="false"
              :disabled="isDeadlinePassed(row.deadLine)"
              :limit="1"
              @change="handleFileUpload($event, row.id)"
              @exceed="handleExceed"
            >
              <el-button
                type="success"
                size="middle"
                text
                link
                :disabled="isDeadlinePassed(row.deadLine)"
              >
                上传文件
              </el-button>
            </el-upload>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </el-card>

  <el-dialog v-model="dialogVisible" width="800" :before-close="handleClose">
    <template #header="{}">
      <div class="my-header">
        <span class="titleClass">PDF 预览</span>
      </div>
    </template>
    <div class="details">
      <div v-if="selectedAnnouncement.noticeFileUrl">
        <iframe
          :src="`${selectedAnnouncement.noticeFileUrl}#toolbar=0&navpanes=0&scrollbar=0`"
          width="100%"
          height="600px"
          frameborder="0"
        ></iframe>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  ElCard,
  ElTable,
  ElTableColumn,
  ElButton,
  ElDialog,
  ElPagination,
  ElMessage,
  ElUpload,
} from "element-plus";
import {
  fetchAnnouncements,
  uploadFile,
  DownloadAttachments,
} from "@/api/announcement";

const announcements = ref([]);
const dialogVisible = ref(false);
const selectedAnnouncement = ref({});
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const uploadRefs = ref({}); // 用于存储每个 el-upload 组件的引用

const getAnnouncements = async (current, size) => {
  try {
    const res = await fetchAnnouncements(current, size);
    // console.log("Announcement:" + res);
    if (res.code) {
      // console.error("Failed to fetch announcements:", error);
      ElMessage.error("获取公告失败");
    }
    total.value = res.count;
    announcements.value = res.data;
    console.log(res);
  } catch (error) {
    console.error("Failed to fetch announcements:", error);
    ElMessage.error("获取公告失败");
  }
};

const showDetails = (row) => {
  selectedAnnouncement.value = row;
  dialogVisible.value = true;
};

const downloadAttachments = async (noticeId, filename) => {
  try {
    await DownloadAttachments(noticeId, filename);
    ElMessage.success("附件下载成功");
  } catch (error) {
    console.error("Failed to fetch attachments:", error);
    ElMessage.error("获取附件信息失败");
  }
};

const handleFileUpload = async (event, id) => {
  const file = event.raw;
  if (!file) {
    alert("请选择一个文件");
    return;
  }

  try {
    const response = await uploadFile(file, id);
    //console.log('文件上传成功:', response);
    ElMessage.success("文件上传成功");
    // 清除文件输入框中的文件
    if (uploadRefs.value[id]) {
      uploadRefs.value[id].clearFiles();
    }
  } catch (error) {
    //console.error('文件上传失败:', error);
    ElMessage.error("文件上传失败");
    // 处理错误
  }
};

const isDeadlinePassed = (deadline) => {
  const now = new Date();
  const deadlineDate = new Date(deadline);
  //console.log(deadline)
  return now > deadlineDate;
};

const isFileCountPassed = (fileCount) => {
  return !(fileCount > 0);
};

const handleClose = () => {
  dialogVisible.value = false;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getAnnouncements(currentPage.value, pageSize.value);
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getAnnouncements(currentPage.value, pageSize.value);
};

const handleExceed = () => {
  ElMessage.warning("只能上传一个文件");
};

onMounted(() => {
  getAnnouncements(currentPage.value, pageSize.value);
});
</script>

<style scoped lang="scss">
.box {
  padding: 15px;
  .el-table {
    margin-bottom: 2vh;
  }
}
.top {
  display: flex;
  width: 100%;
  height: 50px;
  line-height: 50px;
  align-items: center;
  margin-bottom: 15px;
}
.my-header {
  display: flex;
  height: 50px;
  line-height: 50px;
  .titleClass {
    font-size: 25px;
  }
}
.details {
  h3 {
    margin-top: 0;
  }
  p {
    margin: 5px 0;
  }
}
.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.button-group .el-button + .el-button {
  margin-left: 8px;
}
</style>
